package com.owen.he.jee.web.excel;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 * excel导出视图
 * 
 * @author NongFei
 *
 */
public class ExportExcelView extends AbstractExcelView {

	@Override
	protected void buildExcelDocument(Map<String, Object> oModel, HSSFWorkbook oWorkbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ExcelViewExporter excel = null;
		for (Map.Entry<String, Object> oEntry : oModel.entrySet()) {
			if (oEntry.getValue() instanceof ExcelViewExporter) {
				excel = (ExcelViewExporter) oEntry.getValue();
				break;
			}
		}

		if (excel != null) {
			response.setCharacterEncoding("UTF-8");
			String encodedFileName = new String(excel.getFileName().getBytes("GBK"), "ISO8859-1");
			// response.setHeader("Content-type","application/zip;charset=UTF-8");
			// response.setHeader("Content-Disposition",
			// "attachment;filename=\""+encodedFileName+".zip\"");
			response.setHeader("Content-type", "application/msexcel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedFileName + ".xls\"");
			excel.setWorkbook(oWorkbook);
			excel.generateData();
			ServletOutputStream out = response.getOutputStream();
			oWorkbook.write(out);

			out.flush();
		}
	}
}